package com.huaxiafinance.management.controller;

import com.huaxiafinance.management.dto.request.UpdateSignRuleDto;
import com.huaxiafinance.management.model.UserSignRule;
import com.huaxiafinance.management.service.UserSignRuleService;
import com.huaxiafinance.management.util.MessageResult;
import com.huaxiafinance.management.util.ServiceCode;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.List;


@Controller("userSignRuleController")
@RequestMapping("/signManage")
public class UserSignRuleController {

  private static final Logger logger = Logger.getLogger(UserSignRuleController.class);

  @Autowired
  private UserSignRuleService signRuleService;

  /**
   * 修改签到积分规则
   */
  @RequestMapping(value = "/update", produces = "application/json; charset=utf-8", method = RequestMethod.POST)
  public @ResponseBody
  String update(@Valid @RequestBody UpdateSignRuleDto dto) {
    MessageResult messageResult = new MessageResult();
    List<UserSignRule> ruleList = dto.getList();
    if (ruleList == null) {
      messageResult.setResultMessage(ServiceCode.PARAMETERS_ERROR);
      return messageResult.getAsJSON();
    }
    Boolean flag = signRuleService.update(ruleList);
    if (flag) {
      messageResult.setSuccessResult();
    } else {
      messageResult.setFailureResult();
    }
    return messageResult.getAsJSON();
  }

  /**
   * 查询签到规则列表
   */
  @RequestMapping(value = "/query", produces = "application/json; charset=utf-8")
  public @ResponseBody
  String query() {
    MessageResult result = new MessageResult();
    try {
      List<UserSignRule> list = signRuleService.selectList();
      result.setData(list);
      result.setSuccessResult();
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
      result.setFailureResult();
    }
    return result.getAsJSON();
  }

}
